package service;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import common.model.Lukedate;
import common.model.Record;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import util.DateUtil;
import util.IDUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

public class LukeService extends DbRealmService<Lukedate> {

    @Override
    public Page<Lukedate> getDatasByPage(int page, int size) {
        return new Lukedate().paginate(page,size,"select *","from lukedate order by jieci asc");
    }

    public int importFromFile(File file){
        ExcelReader reader= ExcelUtil.getReader(file);
        List<Map<String,Object>> datas=reader.readAll();
        Iterator<Map<String,Object>> iterator=datas.iterator();
        int sum=0;
        while(iterator.hasNext()){
            Map<String,Object> data=iterator.next();
            Lukedate dbData=new Lukedate();
            dbData.setId(IDUtil.getRandomID());
            dbData.setWhen(new Date());
            dbData.setJieci(Integer.valueOf(data.get("节次").toString()));
            dbData.setXingqi1(getStringWithoutErro(data.get("星期一")));
            dbData.setXingqi2(getStringWithoutErro(data.get("星期二")));
            dbData.setXingqi3(getStringWithoutErro(data.get("星期三")));
            dbData.setXingqi4(getStringWithoutErro(data.get("星期四")));
            dbData.setXingqi5(getStringWithoutErro(data.get("星期五")));
            if(saveData(dbData)){
                sum++;
            }
        }
        return sum;
    }

    public String getStringWithoutErro(Object object){
        try{
            return object.toString();
        }catch (Exception e){
            if(e instanceof NullPointerException){
                return "";
            }else{
                e.printStackTrace();
            }
        }
        return null;
    }

    public boolean saveData(Lukedate lukedate){
        Lukedate dbData=new Lukedate().findFirst("select * from lukedate where jieci=?",lukedate.getJieci());
        if(dbData!=null){
            dbData.delete();
        }
        return lukedate.save();
    }

    public Page<Record> getRecordByPage(int page, int size) {
        return new Record().paginate(page,size,"select *","from record order by day desc");
    }

    public Page<Record> getMyRecordByPage(int page, int size) {
        Subject subject= SecurityUtils.getSubject();
        String name= (String) subject.getPrincipal();
        Page<Record> datas = new Record().paginate(page,size,"select *","from record where sheying=? order by day desc",name);
        Iterator<Record> iterator=datas.getList().iterator();
        while(iterator.hasNext()){
            Record record=iterator.next();
            if(record.getState()!=null){
                if(record.getState()==0){
                    record.put("st","待录课");
                }else{
                    record.put("st","已完成");
                }
            }else{
                record.put("st","无状态");
            }
            record.put("date",getDateString(record.getDay()));
        }
        return datas;
    }

    public void deleteRecordById(String id) {
        new Record().findById(id).delete();
    }

    public String exportAllRecords(String date){
        String[] dates=date.split(" - ");
        Date start= DateUtil.getDate(dates[0]);
        Date end= DateUtil.getDate(dates[1]);
        List<Record> record=new Record().find("select * from record where day>=? and day<=? order by  day desc",start,end);
        if(record.size()<=0){
            return null;
        }
        HashMap<String, List<Map<String,Object>>> datas=new HashMap<>();
        Iterator<Record> iterator=record.iterator();
        while(iterator.hasNext()){
            Record rec=iterator.next();
            Map<String,Object> data=new HashMap<>();
            data.put("使用人",rec.getName());
            data.put("日期",getDateString(rec.getDay()));
            data.put("星期",rec.getXingqi());
            data.put("节次",rec.getJieci());
            data.put("摄影",rec.getSheying());
            data.put("使用人签字","");
            Calendar calendar=Calendar.getInstance();
            calendar.setTime(rec.getDay());
            int month=calendar.get(Calendar.MONTH)+1;
            int year=calendar.get(Calendar.YEAR);
            String key=year+"年"+month+"月";
            if(!datas.containsKey(key)){
                datas.put(key,new ArrayList<>());
            }
            datas.get(key).add(data);
        }
        // 通过工具类创建writer
        File webRoot=new File(PathKit.getWebRootPath());
        File dir=new File(webRoot,"record");
        if(!dir.exists()||!dir.isDirectory()){
            dir.mkdir();
        }
        File file=new File(dir,"录课记录"+IDUtil.getRandomID()+".xlsx");
        ExcelWriter writer = ExcelUtil.getWriter(file);
        Iterator<String> iterator1=datas.keySet().iterator();
        writer.getWorkbook().removeSheetAt(0);
        while(iterator1.hasNext()){
            String key=iterator1.next();
            writer.setSheet(key+"录课记录");
            // 合并单元格后的标题行，使用默认标题样式
            writer.merge(datas.get(key).get(0).keySet().size() - 1, key+"录课记录");
            // 一次性写出内容，使用默认样式，强制输出标题
            for(int i=0;i<datas.get(key).get(0).keySet().size();i++){
                writer.getSheet().setColumnWidth(i,16*256);
            }
            writer.write(datas.get(key), true);
        }
        // 关闭writer，释放内存
        writer.close();
        return "/"+dir.getName()+"/"+file.getName();
    }

    public String getDateString(Date date){
        SimpleDateFormat format=new SimpleDateFormat("YYYY年MM月dd日");
        return format.format(date);
    }

    public boolean changeState(String id){
        Record record = new Record().findById(id);
        if(record.getState()==0){
            record.setState(1L);
        }else{
            record.setState(0L);
        }
        return record.update();
    }
}
